package grape.auth.rest.service.impl;

import grape.common.service.loginuser.LoginUser;
import grape.common.tools.ToolService;
import grape.wx.rest.client.user.MpUserClient;
import grape.wx.service.mp.user.po.MpUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 依赖wx的登录,用户微信公众号网页授权登录
 * Created by yangwei
 * Created at 2020/1/8 17:39
 */
@Slf4j
@Component("wxMpCodeUserDetailsService")
public class WxMpCodeUserDetailsServiceImpl implements UserDetailsService , ToolService {

    @Autowired
    private MpUserClient mpUserClient;
    /**
     * code有两部分组成，
     * @param wxUserId
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String wxUserId) throws UsernameNotFoundException {
        boolean superAdmin = false;
        MpUser details = mpUserClient.getById(wxUserId);
        if (details == null) {
            throw  new UsernameNotFoundException("wxUserId=["+ wxUserId +"],未获取到用户id");
        }
        String userId = details.getId();
        Set<String> authority = new HashSet<>();
        authority.add("user");
        LoginUser loginUser = new LoginUser(userId,
                "N/A",
                true,
                true,
                true,
                true,
                AuthorityUtils.createAuthorityList(authority.toArray(new String[0])),
                null
        );
        loginUser.setId(userId);
        loginUser.setSuperAdmin(superAdmin);
        return loginUser;
    }

}
